package com.maven.front.interceptor;

import com.maven.front.bean.EduUser;
import com.maven.front.service.frontLogin.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @program: web-front
 * @description: 前台项目拦截器
 * @author: WangYiLong
 * @create: 2020-08-06 19:51
 **/

@Slf4j
public class MyInterceptorFront implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LoginService loginService;
    /**
     * 拦截器
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info("******进入拦截器");
        //获取前端请求头中的token
        String token = request.getHeader("token");
        log.info("*******"+token);
        if (StringUtils.isEmpty(token)) {
            throw new Exception("40001");
        } else {
            EduUser eduUser = (EduUser) redisTemplate.opsForValue().get(token);
            log.info("*********"+eduUser.toString());
            if (ObjectUtils.isEmpty(eduUser)) {//无效token
                throw new Exception("40002");
            } else { //登录，放行
                //每验证成功，便重置失效时间
                redisTemplate.expire(token, 15, TimeUnit.MINUTES);
                return true;
            }
        }
    }
}

